﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IterationLife.Domains.Sports.Configs;
using IterationLife.Domains.Sports.Dtos.MTSports;
using IterationLife.Domains.Sports.Models;
using IterationLife.Domains.Sports.Repositories;
using IterationLife.Extensions.HttpRequest;
using Util.Domains;

namespace IterationLife.Domains.Sports.Services
{
    /// <summary>
    /// 动量数据序列化
    /// </summary>
    public class MTDataSerializable : DomainServiceBase, IMTDataSerializable
    {
        /// <summary>
        /// 构造
        /// </summary>
        public MTDataSerializable(ISportEventGroupPersonRepository sportEventGroupPersonRepository, ISportEventGroupRepository sportEventGroupRepository, ISportAthleteRepository sportAthleteRepository, ISportUserRepository sportUserRepository, ISportTeamRepository sportTeamRepository, ISportEventRepository sportEventRepository)
        {

            SportUserRepository = sportUserRepository;
            SportTeamRepository = sportTeamRepository;
            SportEventRepository = sportEventRepository;
            SportAthleteRepository = sportAthleteRepository;
            SportEventGroupRepository = sportEventGroupRepository;
            SportEventGroupPersonRepository = sportEventGroupPersonRepository;
        }
        protected ISportUserRepository SportUserRepository { get; set; }

        protected ISportTeamRepository SportTeamRepository { get; set; }

        protected ISportEventRepository SportEventRepository { get; set; }
        protected ISportAthleteRepository SportAthleteRepository { get; set; }
        protected ISportEventGroupRepository SportEventGroupRepository { get; set; }
        protected ISportEventGroupPersonRepository SportEventGroupPersonRepository { get; set; }

        /// <summary>
        /// 数据导入
        /// </summary>
        public void Import(SportUser sportUser)
        {
            ImportTeam(sportUser);
            ImportEvent(sportUser);
        }

        #region 导入用户

        /// <summary>
        /// 导入动量用户
        /// </summary>
        public SportUser ImportUser(MTUserInfo userInfo)
        {
            if (userInfo.personId == null && userInfo.person_id == null)//未取到Id 不进行插入
                return null;
            var result = SaveUser(userInfo);
            MTSaveAthlete(userInfo, result.Id);
            return result;
        }

        /// <summary>
        /// 导入用户
        /// </summary>
        public SportUser ImportUser(int uid)
        {
            //获取我的球队
            var teamJson = Web.HttpGet(MTUrlConfig.GetUserInfo, new Dictionary<string, string>() { { "uid", uid.ToString() } });
            var userInfo = Util.Json.ToObject<MTHttpResult<MTUserInfo>>(teamJson).data;
            return ImportUser(userInfo);
        }

        private SportUser SaveUser(MTUserInfo userInfo)
        {
            if (SportUserRepository.IsUserExist(userInfo.uid))
            {
                var entity = SportUserRepository.Find(t => t.PartnerUserId == userInfo.uid.ToString())
                    .FirstOrDefault();
                MTUserInfoExtension.SetEntityValue(entity, userInfo);
                return entity;
            }
            else
            {
                var sportUser = userInfo.ToSportUser();
                SportUserRepository.Add(sportUser);
                return sportUser;
            }
        }

        /// <summary>
        /// 保存运动员
        /// </summary>
        private void MTSaveAthlete(MTUserInfo userInfo, Guid sportUserId)
        {
            if (userInfo.person_id == null)
                return;
            if (SportAthleteRepository.IsPersonExist(userInfo.person_id.Value))
            {
                var entity = SportAthleteRepository.Find(t => t.PartnerAthleteId == userInfo.person_id.Value.ToString())
                    .FirstOrDefault();
                MTUserInfoExtension.SetEntityValue(entity, userInfo);
            }
            else
            {
                var athlete = userInfo.ToAthlete(sportUserId);
                SportAthleteRepository.Add(athlete);
            }
        }

        #endregion

        #region 保存队伍

        /// <summary>
        /// 保存队伍
        /// </summary>
        public void ImportTeam(SportUser sportUser)
        {
            //获取我的球队
            var teamJson = Web.HttpGet(MTUrlConfig.GetMyTeam, new Dictionary<string, string>() { { "uid", sportUser.PartnerUserId } });
            var teamInfo = Util.Json.ToObject<MTHttpResult<MTTeam>>(teamJson);
            //保存数据库
            foreach (var team in teamInfo.dataList)
            {
                SaveTeam(team);
            }
        }

        /// <summary>
        /// 加入一个队伍
        /// </summary>
        private void SaveTeam(MTTeam team)
        {
            if (!SportTeamRepository.Exists(t => t.PartnerTeamId == team.id.ToString()))
            {
                SportTeamRepository.Add(team.ToSportTeam());
            }
            else
            {
                var entity = SportTeamRepository.Find(t => t.PartnerTeamId == team.id.ToString()).FirstOrDefault();
                MTTeamExtension.SetEntityValue(entity, team);
            }
        }

        #endregion

        #region 导入比赛基本信息

        /// <summary>
        /// 导入比赛基本信息
        /// </summary>
        public void ImportEvent(SportUser sportUserEntity)
        {
            //将比赛基础数据进行插入数据库
            List<SportEvent> events = new List<SportEvent>();
            var page = 1;
            while (true)
            {
                var teamJson = Web.HttpGet(MTUrlConfig.GetEvent, new Dictionary<string, string>() { { "pid", sportUserEntity.SportAthlete.PartnerAthleteId }, { "page", page.ToString() } });
                var teamInfo = Util.Json.ToObject<MTHttpResult<PagerResult<MTEvent>>>(teamJson);
                events.AddRange(SaveEvent(teamInfo.data.list));
                if (teamInfo.data.list.Count == 0)
                    break;
                page++;
            }
            events = events.Where(t => t.StartTime > DateTime.Parse("2017-8-1")).ToList();
            events.ForEach(t => ImportGroupAndGroupUsers(sportUserEntity, t));
            events.ForEach(t => ImportEventReport(sportUserEntity, t));
            events.ForEach(t => SportEventRepository.Add(t));


        }

        #region 保存比赛 -- 仅仅保存比赛一张表

        /// <summary>
        /// 保存比赛 -- 仅仅保存比赛一张表
        /// </summary>
        /// <param name=""></param>
        private List<SportEvent> SaveEvent(List<MTEvent> events)
        {
            var result = new List<SportEvent>();
            foreach (var item in events)
            {
                if (SportEventRepository.Exists(t => t.PartnerEventId == item.event_id.ToString()))
                    continue;
                var sportEvent = item.ToSportEvent();
                if (string.IsNullOrWhiteSpace(sportEvent.FieldPlace))//没有定位 无效比赛
                    continue;
                result.Add(sportEvent);
            }
            return result;
        }

        #endregion

        #region 由比赛表开始详细导入 --- 导入比赛分组和比赛分组用户

        /// <summary>
        /// 导入分组信息
        /// </summary>
        public void ImportGroupAndGroupUsers(SportUser user, SportEvent sportEvent)
        {
            //拿到分组用户
            var teamJson = Web.HttpGet(string.Format(MTUrlConfig.GetEventUsers, sportEvent.PartnerEventId, sportEvent.EventType, user.PartnerUserId));
            var users = Util.Json.ToObject<MTHttpResult<List<MTGroupPerson>>>(teamJson);
            //反推有几个分组
            var groups = new List<SportEventGroup>();
            var groupPersons = new List<SportEventGroupPerson>();
            foreach (var mtUser in users.data)
            {
                SportEventGroup group;
                if (!groups.Exists(t => t.PartnerGroupId == mtUser.ship_id.ToString()))
                    group = ImportSportEventGroup(mtUser, sportEvent);
                else
                    group = groups.First(t => t.PartnerGroupId == mtUser.ship_id.ToString());
                var sportUser = ImportUser(mtUser.person_uid);
                if (sportUser == null)
                    continue;
                var groupPerson = new SportEventGroupPerson(Guid.NewGuid())
                {
                    SportAthleteId = sportUser.Id,
                    SportEventGroupId = group.Id
                };
                groupPersons.Add(groupPerson);
                group.SportEventGroupPeople.Add(groupPerson);
                groups.Add(group);
            }
        }

        #endregion

        #region 导入比赛分组

        /// <summary>
        /// 导入比赛分组
        /// </summary>
        private SportEventGroup ImportSportEventGroup(MTGroupPerson groupPerson, SportEvent sportEvent)
        {
            var group = new SportEventGroup(Guid.NewGuid());
            group.SportEventId = sportEvent.Id;
            group.PartnerGroupId = groupPerson.ship_id.ToString();
            if (groupPerson.team_id != 0)
            {
                var personTeam = SportTeamRepository.Find(t => t.PartnerTeamId == groupPerson.team_id.ToString()).FirstOrDefault();
                group.SportTeamId = personTeam == null ? default(Guid?) : personTeam.Id;
            }
            sportEvent.SportEventGroups.Add(group);
            return group;
        }

        #endregion

        #region 导入详细比赛数据

        /// <summary>
        /// 导入详细比赛数据
        /// </summary>
        private void ImportEventReport(SportUser user, SportEvent sportEvent)
        {
            ImportPalyerReport(user, sportEvent);
            ImportTeamReport(user, sportEvent);
        }

        #region 个人报告数据

        /// <summary>
        /// 个人报告数据
        /// </summary>
        private void ImportPalyerReport(SportUser user, SportEvent sportEvent)
        {
            if (SportEventGroupPersonRepository.Exists(t => t.SportAthleteId == user.Id && t.SportEventGroup.SportEvent.PartnerEventId == sportEvent.PartnerEventId))
                return;
            try
            {
                var personReportJson = Web.HttpGet(string.Format(MTUrlConfig.GetEvetnPersonReport, sportEvent.PartnerEventId, sportEvent.EventType, user.SportAthlete.PartnerAthleteId, user.PartnerUserId));
                var report = Util.Json.ToObject<MTHttpResult<MTPersonReport>>(personReportJson);
                var mtHistory = user.SportAthlete.GetJsonData();
                mtHistory.Avg = report.data.person_history_avg.ToMTGatherData();
                user.SportAthlete.SetJsonData(mtHistory);
                foreach (var group in sportEvent.SportEventGroups)
                {
                    foreach (var person in group.SportEventGroupPeople)
                    {
                        person.SetJsonData(report.data.person_data.FirstOrDefault(t => t.data_type == 1)?.ToMTGatherData());
                    }
                }
            }
            catch (Exception e)
            {
                sportEvent.IsDeleted = true;
                return;
            }

        }

        #endregion

        #region 团队报告数据

        /// <summary>
        /// 团队报告数据
        /// </summary>
        private void ImportTeamReport(SportUser user, SportEvent sportEvent)
        {
            if (SportEventGroupRepository.Exists(t => t.SportEvent.PartnerEventId == sportEvent.PartnerEventId))
                return;
            try
            {
                var teamReportJson = Web.HttpGet(string.Format(MTUrlConfig.GetEvetnTeamReport, sportEvent.PartnerEventId, sportEvent.EventType));
                var report = Util.Json.ToObject<MTHttpResult<MTTeamReport>>(teamReportJson);
                if (report.data.history_avg != null)
                {
                    var team = SportTeamRepository.Find(t => t.PartnerTeamId == report.data.history_avg.team_id.ToString())
                        .FirstOrDefault();
                    if (team != null)
                    {
                        var historyData = team.GetJsonData();
                        historyData.Avg = report.data.history_avg.ToMTGatherData();
                        historyData.Highest = report.data.highest.ToMTGatherData();
                        team.SetJsonData(historyData);
                    }
                }
                var eventJsonData = sportEvent.GetJsonData();
                eventJsonData.Lowest = report.data.team_event_min.Count > 0 ? report.data.team_event_min[0].ToMTGatherData() : null;
                eventJsonData.Highest = report.data.team_event_max.Count > 0 ? report.data.team_event_max[0].ToMTGatherData() : null;
                eventJsonData.Avg = report.data.team_event_avg.Count > 0 ? report.data.team_event_avg[0].ToMTGatherData() : null;
                sportEvent.SetJsonData(eventJsonData);
            }
            catch (Exception e)
            {
                sportEvent.IsDeleted = true;
                return;
            }
        }

        #endregion

        #endregion

        #endregion
    }
}
